/**
 * @description: 这是Eirudy创建的类~
 * @author: Eirudy
 * @hope: 憧憬成为java大师
 **/

package org.eirudy.shareimage.manager.websocket;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingSphereTransactionType;
import org.eirudy.shareimage.manager.auth.SpaceUserAuthManager;
import org.eirudy.shareimage.manager.auth.model.SpaceUserPermissionConstant;
import org.eirudy.shareimage.model.entity.Picture;
import org.eirudy.shareimage.model.entity.Space;
import org.eirudy.shareimage.model.entity.User;
import org.eirudy.shareimage.model.enums.SpaceTypeEnum;
import org.eirudy.shareimage.service.impl.PictureServiceImpl;
import org.eirudy.shareimage.service.impl.SpaceServiceImpl;
import org.eirudy.shareimage.service.impl.SpaceUserServiceImpl;
import org.eirudy.shareimage.service.impl.UserServiceImpl;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 *  建立连接前先校验
 */
@Slf4j
@Component
public class WsHandshakeInterceptor  implements HandshakeInterceptor {

    @Resource
    private UserServiceImpl userServiceImpl;

    @Resource
    private PictureServiceImpl pictureServiceImpl;

    @Resource
    private SpaceServiceImpl spaceServiceImpl;


    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //获取当前登录用户
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();

            // 从请求中获取用户信息
            String pictureId = servletRequest.getParameter("pictureId");
            if(StrUtil.isBlank(pictureId)){
                log.error("pictureId is null, 拒绝握手");
                return false;
            }

            User loginUser = userServiceImpl.getLoginUser(servletRequest);
            if(ObjUtil.isEmpty(loginUser)){
                log.error("用户未登录, 拒绝握手");
                return false;
            }

            //校验用户是否有编辑当前图片的权限
            Picture picture = pictureServiceImpl.getById(pictureId);
            if(ObjUtil.isEmpty(picture)){
                log.error("图片为空, 拒绝握手");
                return false;
            }


            Long spaceId = picture.getSpaceId();
            Space space = null;
            if(spaceId != null) {
                space = spaceServiceImpl.getById(spaceId);
                if(ObjUtil.isEmpty(space)){
                    log.error("图片所在空间不存在, 拒绝握手");
                    return false;
                }

                if(space.getSpaceType() != SpaceTypeEnum.TEAM.getValue()){
                    log.error("不是团队空间, 拒绝握手");
                    return false;
                }
            }


            // 如果是团队空间，并且有编辑者权限，才能校验
            List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
            if(!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)){
                log.error("没有编辑权限, 拒绝握手");
                return false;

            }

            // 设置用户登录信息到webSocket会话中
            attributes.put("user", loginUser);

            attributes.put("pictureId", Long.valueOf(pictureId));  // 转化为Long类型

        }


        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
